﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;

using System.Runtime.InteropServices;
using System.Web;

using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;


namespace DotNetNuke.Modules.UserDefinedTable
{


  public class DataTypeUserLink : DataType, IUserSource, IEmailAdressSource
  {



    [StructLayout(LayoutKind.Sequential)]
    private struct FieldSetting
    {
      public string Title;
      public string TokenText;
      public bool ShowUserName;
    }




    public string GetEmailAddress(string FieldName, DataRow row)
    {
      return this.GetUser(FieldName, row).Email;
    }





    public UserInfo GetUser(string FieldName, DataRow row)
    {
      string str;
      if (row.Table.Columns.Contains(FieldName + DataTableColumn.Appendix_Original))
        str = Utilities.CStrN((row[FieldName + DataTableColumn.Appendix_Original]), "");
      
      else
        str = Utilities.CStrN((row[FieldName]), "");

      if ( !string.IsNullOrEmpty(str) )
        return new UserController().GetUser(DotNetNuke.Common.Globals.GetPortalSettings().PortalId, int.Parse(str.Substring(7)));
      
      return null;
    }





    public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int ModuleId, bool noScript)
    {
      if (ds != null)
      {
        IEnumerator enumerator = null;
        ArrayList list = new ArrayList();
        DataTable table = ds.Tables[DataSetTableName.Data];
        DotNetNuke.Modules.UserDefinedTable.TokenReplace replace2 = new DotNetNuke.Modules.UserDefinedTable.TokenReplace();
        replace2.ModuleId = ModuleId;
        DotNetNuke.Modules.UserDefinedTable.TokenReplace replace = replace2;
        try
        {
          enumerator = ds.Tables[DataSetTableName.Fields].Rows.GetEnumerator();
          while (enumerator.MoveNext())
          {
            DataRow current = (DataRow)enumerator.Current;
            if ((string)current[FieldsTableColumn.Type] == this.Name)
            {
              FieldSetting setting3 = new FieldSetting();
              FieldSetting setting4 = setting3;
              setting4.Title = (string)current[FieldsTableColumn.Title];
              setting4.TokenText = Utilities.CStrN((current[FieldsTableColumn.OutputSettings]), "");
              setting4.ShowUserName = Utilities.CBoolN((current[FieldsTableColumn.NormalizeFlag]), false);
              FieldSetting setting = setting4;
              list.Add(setting);
              table.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Url, typeof(string)));
              table.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Original, typeof(string)));
              table.Columns.Add(new DataColumn(setting.Title + DataTableColumn.Appendix_Caption, typeof(string)));
            }
          }
        }
        finally
        {
          if (enumerator is IDisposable)
            (enumerator as IDisposable).Dispose();
          
        }
        if (list.Count > 0)
        {
          bool flag;
          IEnumerator enumerator2 = null;
          PortalSettings currentPortalSettings = null;
          if (HttpContext.Current != null)
          {
            currentPortalSettings = PortalController.GetCurrentPortalSettings();
          }
          Hashtable moduleSettings = new ModuleController().GetModuleSettings(ModuleId);
          bool expression = Utilities.CBoolN((moduleSettings[SettingName.UserLinkNewWindow]), false);

          if (!moduleSettings.ContainsKey(SettingName.UserLinkCaption))
            flag = false;

          else
            flag = ((string)moduleSettings[SettingName.UserLinkCaption]).Equals("UserName", StringComparison.OrdinalIgnoreCase);

          try
          {
            enumerator2 = table.Rows.GetEnumerator();
            IEnumerator enumerator3 = null;
            while (enumerator2.MoveNext())
            {
              
              DataRow row = (DataRow)enumerator2.Current;
              try
              {
                enumerator3 = list.GetEnumerator();
                while (enumerator3.MoveNext())
                {
                  FieldSetting setting2 = (FieldSetting)enumerator3.Current;
                  string str2 = string.Empty;
                  string strURL = (string)row[setting2.Title];
                  string tokenText = setting2.TokenText;
                  string str4 = string.Empty;
                  strURL = URLUtil.StripURL(ref strURL);

                  if ( !string.IsNullOrEmpty(strURL) )
                  {
                    bool flag3 = true;
                    int userId = -1;

                    if (strURL.StartsWith("userid=", StringComparison.OrdinalIgnoreCase) && (currentPortalSettings != null))
                    {
                      try
                      {
                        userId = int.Parse(strURL.Substring(7));
                        replace.User = new UserController().GetUser(currentPortalSettings.PortalId, userId);
                      }
                      catch (Exception e)
                      { }
                    }
                    if (userId == -1)
                    {
                      replace.User = new UserInfo();
                      replace.User.Username = "???";
                    }

                    if ( string.IsNullOrEmpty(tokenText) )
                    {
                      if (setting2.ShowUserName)
                        tokenText = "[User:DisplayName]";

                      else
                        tokenText = "[User:UserName]";

                    }
                    tokenText = replace.ReplaceEnvironmentTokens(tokenText, row);

                    if ( string.IsNullOrEmpty(tokenText) )
                      tokenText = replace.ReplaceEnvironmentTokens("[User:username]");

                    str4 = HttpUtility.HtmlEncode(DotNetNuke.Common.Globals.LinkClick(strURL, currentPortalSettings.ActiveTab.TabID, ModuleId));
                    if (flag3)
                      str2 = string.Format("<!--{1}--><a href=\"{0}\"{2}>{1}</a>", str4, tokenText, expression ? " target=\"_blank\"" : "").ToString();

                    else
                      str2 = tokenText;

                  }
                  row[setting2.Title] = str2;
                  row[setting2.Title + DataTableColumn.Appendix_Original] = strURL;
                  row[setting2.Title + DataTableColumn.Appendix_Url] = str4;
                  row[setting2.Title + DataTableColumn.Appendix_Caption] = tokenText;
                }
                continue;
              }
              finally
              {
                if (enumerator3 is IDisposable)
                  (enumerator3 as IDisposable).Dispose();

              }
            }
          }
          finally
          {
            if (enumerator2 is IDisposable)
              (enumerator2 as IDisposable).Dispose();

          }
        }
      }
    }




    public override string Name
    { get { return "UserLink"; } }




    public override string SupportedCasts
    {
      get { return string.Format("{0}|UserLink", base.SupportedCasts); }
    }




    public override bool SupportsDefaultValue
    { get { return true; } }




    public override bool SupportsEditing
    { get { return true; } }




    public override bool SupportsInputSettings
    { get { return true; } }




    public override bool SupportsNormalizeFlag
    { get { return true; } }




    public override bool SupportsOutputSettings
    { get { return true; } }




    public override bool SupportsSearch
    { get { return true; } }




  }

}

